import time
from threading import Thread

import centralized


def create_thread(num):
    global coordinator, participant_list, participant_thread_list, check_thread
    # 创建协调者线程
    coordinator = centralized.Coordinator()
    coordinator_thread = Thread(target=coordinator.start, name='coordinator')
    coordinator_thread.setDaemon(True)  # 守护线程
    coordinator_thread.start()  # 协调者线程启动

    check_thread.start()  # 检查线程启动

    # 创建参与者线程
    for i in range(0, num):
        participant = centralized.Participant(i, coordinator.request_list, coordinator.lock)
        participant_list.append(participant)  # 添加到参与者列表
        participant_i = Thread(target=participant.start, name=f'participant_{i}')
        participant_thread_list.append(participant_i)
        participant_i.setDaemon(True)  # 守护线程
        participant_i.start()  # 参与者线程启动
    return coordinator_thread


def update_request_list():
    while 1:
        global coordinator, request_list
        try:
            for participant in participant_list:
                pass
                # time.sleep(1)
            # check_response()
        except:
            continue


def check_response():
    global coordinator, request_list
    while 1:
        if len(coordinator.response_obj.split('_')) > 1:
            response = coordinator.response_obj.split('_')[1]
            if response.isdigit():
                response = int(response)
                if not participant_list[response].get_response:
                    participant_list[response].get_response = True
        request_list = coordinator.request_list


def main(num):
    global participant_list, check_thread
    check_thread = Thread(target=check_response)  # 负责检查响应的线程
    check_thread.setDaemon(True)

    coordinator_thread = create_thread(num)  # 创建参与者和协调者,检查线程会在协调者创建后启动
    for i in range(0, num):
        participant_thread_list[i].join()
    coordinator_thread.join()
    check_thread.join()


if __name__ == '__main__':
    coordinator = ''
    check_thread = ''
    participant_list = []  # 参与者列表
    participant_thread_list = []  # 参与者线程列表
    request_list = []  # 参与者请求列表
    participant_num = int(input("请输入参与者个数："))
    main(participant_num)
